package com.cheche.dn.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Util - Properties读取
 * Created by cheshun on 15/8/19.
 */
public final class PropertiesUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    public static final String DEFAULT_CONFIG = "config.properties";

    public static String getProperties(String configFile, String propertyName) {
        String res = null;

        Properties properties = new Properties();
        InputStream in = null;
        try {
            in = PropertiesUtil.class.getClassLoader().getResourceAsStream(configFile);
            properties.load(in);
            res = properties.getProperty(propertyName);
        } catch (IOException ioe) {
            logger.error(String.format("Unable to read %s", configFile), ioe);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (final IOException ioe) {
                    logger.error(String.format("Unable to close %s", configFile), ioe);
                }
            }
        }
        return res;
    }

    public static String getProperties(String propertyName) {
        return getProperties(DEFAULT_CONFIG, propertyName);
    }

    public static Integer getPropertiesInt(String propertyName) {
        return getPropertiesInt(DEFAULT_CONFIG, propertyName);
    }

    public static Integer getPropertiesInt(String configFile, String propertyName) {
        String res = getProperties(configFile, propertyName);
        if (null != res) {
            return Integer.valueOf(res);
        }
        return 0;
    }

    public static Long getPropertiesLong(String propertyName) {
        return getPropertiesLong(DEFAULT_CONFIG, propertyName);
    }

    public static Long getPropertiesLong(String configFile, String propertyName) {
        String res = getProperties(configFile, propertyName);
        if (null != res) {
            return Long.valueOf(res);
        }
        return 0L;
    }

    public static Boolean getPropertiesBool(String propertyName) {
        return getPropertiesBool(DEFAULT_CONFIG, propertyName);
    }

    public static Boolean getPropertiesBool(String configFile, String propertyName) {
        String res = getProperties(propertyName);
        return null != res && res.equalsIgnoreCase("true");
    }
}
